<?php
namespace Ucmaim\Controller\Home;

class BuyController extends CommonController{

    public function _initialize(){
        parent::_initialize();
        $this->requireLogin();
    }

    //下单
    public function Order(){
        if ( IS_POST ) {
            $order_sn = generate_order_sn();
            if($_POST['seller_id'] == $_POST['buyer_id']) $this->error('不能购买自己发布的商品');
            if((int)$_POST['order_number']<0) $this->error('购买数量必须大于0');
            if(empty($_POST['order_mobile'])) $this->error('电话号码必须填写');
            if(empty($_POST['buyer_alipay'])) $this->error('支付宝帐号必须填写');
            if(empty($_POST['order_zytuid'])) $this->error('游乐淘帐号必须填写');
            $_POST['order_sn'] = $order_sn;
            compare_form_hash($_POST['hash']);
            $Order = D('Order');
            $Order->startTrans();//事务处理开始
            $result = $Order->NewOrder();
            $result_G = D('Goods')->updateGoodsStorage('Add',$_POST['order_number'],$_POST['goods_id']);
            if($result && $result_G){
                $Order->commit();
            }else{
                $Order->rollback();
                $result = '';
            }
            $result > 0 ? $this->redirect('/Home/Buy/Pay/', array('sn'=>$order_sn)) : $this->error('未知错误');
        }else {
            $gid = (int)I('get.id');
            if($gid <= 0) $this->error('操作错误');
            $goods = D('Goods')->getGoodsInfo($gid);
            if(empty($goods)) $this->error('该商品不存在');
            $member_info = $this->getMemberInfo();
            if($member_info['uid'] == $goods['member_id']) $this->error('不能购买自己发布的商品');

            //《游戏卖交易购买协议》
            $title = '游戏卖交易购买协议';
            $cid = D('ContentCategory')->getCategoryList(0, 'agreement')[0]['id'];
            if( $cid ){
                $map['title'] = $title;
                $agreement = D('Content')->where($map)->getList()[0];
            }else{
                $agreement = [];
            }
            $this->assign('agreement', $agreement);
            $this->assign('goods', $goods);
            $this->assign('hash', form_hash());
            $this->display('Order');
        }

    }

    // 卖家发货
    public function SendGoods(){
        $uid = $this->member_info['uid'];
        $order_sn = I('get.sn');
        $Order = D('Order');
        $order_info = $Order->getOrderInfo($order_sn);
        if( empty($order_info) ) $this->error('此订单不存在');
        if( $order_info['order_real_status'] == -2 ) $this->error('此订单已超过发货时间，系统已自动取消');
        if( $order_info['seller_id'] != $uid ) $this->error('您不能操作此订单');
        if( $order_info['order_real_status'] != 2 ) $this->error('操作错误');
        $Order->updateOrderStatus($order_sn, 3) ? $this->success('操作成功，订单已发货') : $this->error('操作失败，请稍候再试');
    }

    //确认收货
    public function ReceivedGoods(){
        $uid = $this->member_info['uid'];
        $order_sn = I('get.sn');
        $Order = D('Order');
        $order_info = $Order->getOrderInfo($order_sn);
        if( empty($order_info) ) $this->error('此订单不存在');
        if( $order_info['buyer_id'] != $uid ) $this->error('您不能操作此订单');
        if( $order_info['order_real_status'] == -3 ) $this->error('此订单已超过确认收货时间');
        if( $order_info['order_real_status'] != 3 ) $this->error('操作错误');
        $Order->startTrans();//事务处理开始
        $result = $Order->updateOrderStatus($order_sn, 4);
        //同时更新商品库存
        $result_G = D('Goods')->updateGoodsStorage('Received', $order_info['order_number'], $order_info['goods_id']);
        if ($result && $result_G) {
            $Order->commit();
        } else {
            $Order->rollback();
            $result = '';
        }
        $result ? $this->success('确认收货成功') : $this->error('操作失败，请稍候再试');
    }

    //取消订单
    public function CancelOrder(){
        $order_sn = I('get.sn');
        $Order = D('Order');
        $order_info = $Order->getOrderInfo($order_sn);
        if(empty($order_info)) $this->error('此订单不存在');
        if($this->member_info['uid'] != $order_info['buyer_id']) $this->error('您不能操作此订单');
        $Order->startTrans();//事务处理开始
        $result = $Order->updateOrderStatus($order_sn, -1);
        //同时更新商品库存
        $result_G = D('Goods')->updateGoodsStorage('Cancel', $order_info['order_number'], $order_info['goods_id']);
        if ($result && $result_G) {
            $Order->commit();
        } else {
            $Order->rollback();
            $result = '';
        }
        $result ? $this->success('此订单已取消') : $this->error('操作失败');
    }

    // 下单成功
    public function Pay(){
        $order_sn = I('get.sn', '', 'trim');
        if(empty($order_sn)) $this->error('该订单不存在', U('Home/Index'));

        $order_info = D('Order')->getOrderInfo($order_sn, true);
        if(empty($order_info)) $this->error('该订单不存在', U('Home/Goods/Items'));
        if($order_info['order_real_status'] == -1) $this->error('此订单已被取消，请重新下单', U('Home/Goods/Items'));
        if($order_info['order_status'] != 1) $this->error('您已经支付，请勿重复提交！', U('Home/Goods/Items'));

        $expire = getConfig('PAY_EXPIRE');
        $this->assign('expire', $expire);
        $this->assign('order_info', $order_info);
        $this->display('Pay');
    }

    // 支付订单
    public function GotoPay(){
        $member_info = $this->member_info;
        $order_sn = I('post.order_sn', '', 'trim');
        $order_info = D('Order')->getOrderInfo($order_sn);

        // 订单不存在
        if(empty($order_info)) $this->error('该订单不存在', U('Home/Index'));
        // 支付超时
        if($order_info['order_real_status'] == -1) $this->error('此订单已被取消，请重新下单', U('Home/Goods/Items'));
        // 检测是否是自己的订单
        if($order_info['buyer_id'] != $member_info['uid'] || $order_info['seller_id'] == $member_info['uid']) $this->error('您不能支付此订单');
        // 订单已支付
        if($order_info['order_status'] != 1) $this->success('此订单已支付，您不用再支付此订单');

        // 计算订单金额
        $total_fee = floatval($order_info['order_price'] * $order_info['order_number']);
        $subject = '游戏卖订单【'.$order_info['order_sn'].'】在线支付';
        $body    = '支付游戏卖订单【'.$order_info['order_sn'].'】'.$total_fee.'元';
        //计算订单金额
        $this->_alipay($order_info['order_sn'], $subject, $total_fee, $body);
    }

    /**
     * 支付宝支付方法
     *
     * @param $order_sn
     * @param $subject
     * @param $total_fee
     * @param $body
     */
    private function _alipay($order_sn, $subject, $total_fee, $body){
        vendor('Alipay.Core');
        vendor('Alipay.Submit');
        vendor('Alipay.MD5');
        vendor('Alipay.Notify');

        $alipay_config = C('ALIPAY');
        $parameter = array(
            "service" => "create_direct_pay_by_user",
            "partner" => $alipay_config['PARTNER'],
            "seller_email" => trim($alipay_config['SELLER_MAIL']),
            "payment_type"	=> 1,
            "notify_url"	=> $alipay_config['NOTIFY_URL'],
            "return_url"	=> $alipay_config['RETURN_URL'],
            "out_trade_no"	=> $order_sn,
            "subject"	=> $subject,
            "total_fee"	=> $total_fee,
            "body"	=> $body,
            "show_url"	=> '',
            "anti_phishing_key"	=> '',
            "exter_invoke_ip"	=> get_client_ip(),
            "_input_charset"	=> $alipay_config['CHARSET'],
        );

        //重构原生支付宝配置信息
        $_config = array(
            'partner' => $alipay_config['PARTNER'],
            'seller_email' => $alipay_config['SELLER_MAIL'],
            'key' => $alipay_config['KEY'],
            'sign_type' => $alipay_config['SIGN_TYPE'],
            'input_charset' => $alipay_config['CHARSET'],
            'cacert' => $alipay_config['CACERT'],
            'transport' => $alipay_config['TRANSPORT'],
        );

        $alipaySubmit = new \AlipaySubmit($_config);
        $html_text = $alipaySubmit->buildRequestForm($parameter,"get", "");
        echo $html_text;
    }
}